<?php

use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\AsyncTcpConnection;

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ ."/port.php";
global $worker;
global $inner_text_worker;
global $inner_worker_arr;
$inner_worker_arr->uidConnections=array();
$worker = new Worker('tcp://0.0.0.0:'.$_tcp_port);

$worker->onWorkerStart= function($worker) use($_text_port) {
    echo("onWorkerStart\n\r");
    // 开启一个内部端口，方便内部系统推送数据，Text协议格式 文本+换行符
    $inner_text_worker = new Worker('Text://0.0.0.0:'.$_text_port);
    $inner_text_worker->onMessage = function($connection, $buffer)
    {
        global $inner_worker_arr;
        $inner_worker_arr->uidConnections[$connection->id] = $connection;
        $ret = sendMessage($buffer);
        
        // var_dump($ret_data);
        // if($ret_data){
        //   $connection->send($ret_data);
        // }
        
    };
    
    $inner_text_worker->onClose = function($connection)
    {
        global $inner_worker_arr;
        if(isset($connection->id))
        {
            unset($inner_worker_arr->uidConnections[$connection->id]);
        }
    };
    $inner_text_worker->listen();
};


$worker->uidConnections = array();
$worker->onConnect = function(TcpConnection $connection) use($worker)
{
    $worker->uidConnections[$connection->id] = $connection;
    echo("链接成功：". $connection->id . "\n\r");
};

$worker->onMessage = function(TcpConnection $connection, $message)
{
    global $inner_worker_arr;
    echo("收到消息bin2hex：". bin2hex($message) . "\n\r");
    $message = str_replace(' ', '',  bin2hex($message));
    if($message != '5581' && $inner_worker_arr->uidConnections){
        foreach($inner_worker_arr->uidConnections as $connection)
        {
           if($connection){
                   echo("推送：". $connection->id . "\n\r");

                $d = $connection->send($message);
            }
        }
    }
};


// 当有客户端连接断开时
$worker->onClose = function($connection)use($worker)
{
    global $worker;
    if(isset($connection->uid))
    {
        unset($worker->uidConnections[$connection->uid]);
    }
};

// 针对uid推送数据
function sendMessage($message)
{
    global $worker;
    echo "发送消息{$message}.\n\r";
    foreach($worker->uidConnections as $connection)
    {
       if($connection){
            $d = $connection->send(hex2bin(str_replace(' ', '', $message)));
            var_dump($connection->resumeRecv());
        }
    }
}

// 运行worker
Worker::runAll();
